//
//  InputTransferInfoViewController.m
//  PigMarket
//
//  Created by mac on 2019/5/8.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "InputTransferInfoViewController.h"
#import "TransferInfoCell.h"
#import "TransferInfoFooterView.h"
#import "TransferResultViewController.h"

@interface InputTransferInfoViewController ()<UITableViewDelegate,UITableViewDataSource>
/**
 myTableView
 */
@property (nonatomic , strong) UITableView *myTableView;
/**
 dataArr
 */
@property (nonatomic , strong) NSArray *dataArr;
/**
 verifyCodeBtn
 */
@property (nonatomic , strong) VerifyCodeButton *verifyCodeBtn;
/**
 requestCode
 */
@property (nonatomic , strong) NSString *requestCode;
/**
 phoneField
 */
@property (nonatomic , strong) UITextField *phoneField;
/**
 foooter
 */
@property (nonatomic , strong) TransferInfoFooterView *footerView;
@end

@implementation InputTransferInfoViewController


#pragma mark - view life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.baseNavView.navTitleLabel.text = @"填写信息";
    [self setUpView];
}


#pragma mark - init method
- (void)setUpView {
    [self initView];
    [self initLayout];
    [self initAction];
    [self initData];
}


- (void)initView {
    [self.view addSubview:self.myTableView];
}



- (void) initLayout {
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(TJ_NavBarHeight, 0, 0, 0));
    }];
}


- (void) initAction {
    RACSignal *sendVerifyStateSignal = [self.phoneField.rac_textSignal map:^id _Nullable(NSString * _Nullable phoneNum) {
        return @([phoneNum isValidPhoneNumber]);
    }];
    RACSignal *countDowningSignal = RACObserve(self.verifyCodeBtn, isCountDowning);
    RAC(self.verifyCodeBtn,enabled) = [RACSignal combineLatest:@[sendVerifyStateSignal,countDowningSignal] reduce:^id _Nonnull(NSNumber *sendVerifyState, NSNumber *countDowningState){
        return @(sendVerifyState.boolValue && !countDowningState.boolValue);
    }];
}



- (void)initData {
    NSString *money = [NSString stringWithFormat:@"￥%@",self.model.pigPay ? self.model.pigPay : @"0"];
    NSString *moneyTips = @"金额说明";
    self.dataArr = @[@[@{@"title":@"此猪共花费:",@"icon":@"",@"text":@"",@"rightText":money}],
                     @[@{@"title":@"转让金额",@"icon":@"",@"text":@"",@"rightText":@""},
                       @{@"title":@"",@"icon":@"adopted_transfer_money",@"text":@"请输入转让金额",@"rightText":@""},
                       @{@"title":@"",@"icon":@"",@"text":moneyTips,@"rightText":@""}],
                     @[@{@"title":@"转让人",@"icon":@"",@"text":@"",@"rightText":@""},
                       @{@"title":@"",@"icon":@"adopted_transfer_phone",@"text":@"请输入手机号",@"rightText":@""},
                       @{@"title":@"",@"icon":@"adopted_transfer_code",@"text":@"请输入验证码",@"rightText":@"获取验证码"}],
                     @[@{@"title":@"接收人",@"icon":@"",@"text":@"请输入手机号",@"rightText":@"adopted_transfer_addressbook"}]];
}



#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return 3;
            break;
        case 2:
            return 3;
            break;
        case 3:
            return 1;
            break;
        default:
            break;
    }
    return 0;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 3) {
        return 131;
    }
    return 0.01;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 3) {
        self.footerView = [[TransferInfoFooterView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 131)];
        [self.footerView.agreementDetailBtn addTarget:self action:@selector(transferAgreementTapped) forControlEvents:UIControlEventTouchUpInside];
        [self.footerView.confirmBtn addTarget:self action:@selector(confirmTapped) forControlEvents:UIControlEventTouchUpInside];
        
        return self.footerView;
    }
    return [[UIView alloc] init];
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TransferInfoCell *cell = [TransferInfoCell cellWithTableView:tableView];
    
    cell.infoDic = self.dataArr[indexPath.section][indexPath.row];
    NSString *phone = @"";
    if (indexPath.section == 2 ) {
        if (indexPath.row == 1) {
            self.phoneField = cell.inputField;
            phone = cell.inputField.text;

        } else if (indexPath.row == 2) {
            self.verifyCodeBtn = cell.verifyCodeBtn;
        }
    }
    @weakify(self);
    [cell setGetVerifyCodeBlock:^{
        @strongify(self);
        [self getVerifyCodeRequestWithPhone:phone];
    }];
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}


#pragma mark - target action

- (void)transferAgreementTapped {
    
}


- (void)confirmTapped {
    TransferInfoCell *moneyCell = (TransferInfoCell *)[self.myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]];
    TransferInfoCell *transferPeoplephoneCell = (TransferInfoCell *)[self.myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:2]];
    TransferInfoCell *codeCell = (TransferInfoCell *)[self.myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:2]];
    TransferInfoCell *receiverPhoneCell = (TransferInfoCell *)[self.myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:3]];
    NSString *money = moneyCell.inputField.text;
    NSString *transferPeoplePhone = transferPeoplephoneCell.inputField.text;
    NSString *code = codeCell.inputField.text;
    NSString *receiverPhone = receiverPhoneCell.inputField.text;
    if ([JTool iSNull:money]) {
        [self toastWithContent:@"请输入转让金额"];
        return;
    }
    if (![transferPeoplePhone isValidPhoneNumber]) {
        [self toastWithContent:@"请输入手机号"];
        return;
    }
    if ([JTool iSNull:code] && [self.requestCode isEqualToString:code]) {
        [self toastWithContent:@"请输入正确验证码"];
        return;
    }
    if (![receiverPhone isValidPhoneNumber]) {
        [self toastWithContent:@"请输入接收人手机号"];
        return;
    }
    if (!self.footerView.agreementBtn.selected) {
        [self toastWithContent:@"请同意转让协议"];
        return;
    }
    NSString *message = [NSString stringWithFormat:@"您确定要转让编号为%@的仔猪吗？",self.model.pigNum];
    @weakify(self);
    [[AlertAction sharedInstance] showAlertWithTitle:@"仔猪转让" message:message confirmBtnTitle:@"确定" confirmBlock:^{
        @strongify(self);
        [self transferRequestWithReceiverPhone:receiverPhone transferMoney:money];
    } cancelBlock:nil];
    
}


#pragma mark - private method
- (void)getVerifyCodeRequestWithPhone:(NSString *)phone{
    GetMessageCodeParam *param = [[GetMessageCodeParam alloc] init];
    param.phone = phone;
    param.type = GetMessageCodeTypeChangePassword;
    @weakify(self);
    [[[PigMarketApi sharedInstance] getMessageCodeWithParam:param] subscribeNext:^(GetMessageCode * _Nullable messageCode) {
        @strongify(self);
        self.requestCode = messageCode.mobileCode;
        [self.verifyCodeBtn startCountDown];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}


- (void)transferRequestWithReceiverPhone:(NSString *)receiverPhone transferMoney:(NSString *)transferMoney{
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    NSNumber *pigId = self.model.pigId;
    @weakify(self);
    [[[PigMarketApi sharedInstance] confirmTransferWithMemberId:memberId receiverPhone:receiverPhone transferMoney:transferMoney pigId:pigId] subscribeNext:^(NSNull * _Nullable x) {
        @strongify(self);
        [self.navigationController pushViewController:[[TransferResultViewController alloc] init] animated:YES];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}


#pragma mark - getter and setter

- (UITableView *)myTableView {
    if (!_myTableView) {
        _myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableView.scrollEnabled = NO;
        _myTableView.rowHeight = 54;
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
    }
    return _myTableView;
}


- (NSArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [[NSArray alloc] init];
    }
    return _dataArr;
}


- (VerifyCodeButton *)verifyCodeBtn {
    if (!_verifyCodeBtn) {
        _verifyCodeBtn = [VerifyCodeButton buttonWithType:UIButtonTypeCustom];
    }
    return _verifyCodeBtn;
}


- (UITextField *)phoneField {
    if (!_phoneField) {
        _phoneField = [[UITextField alloc] init];
    }
    return _phoneField;
}


@end

